package shujia.day08;

import java.util.Arrays;

/*
    Arrays: jdk针对数组做操作的一个工具类

    成员方法：
        public static String toString(int[] a) 以指定格式查看任意类型元素的数组
        public static void sort(int[] a) 快速排序一个数组，从小到大
        public static int binarySearch(int[] a,int key)  二分查找，返回所查找元素的索引，前提该序列要有序


 */
public class ArraysDemo1 {
    public static void main(String[] args) {
        int[] arr = {123,5432,67,2,64,8443};
//        String s1 = Arrays.toString(arr);
//        System.out.println(s1);
        System.out.println("排序前："+Arrays.toString(arr));
        Arrays.sort(arr);
        System.out.println("排序后："+Arrays.toString(arr));

        //[2, 64, 67, 123, 5432, 8443]
        System.out.println(Arrays.binarySearch(arr,99)); // -4



    }
}

/*
    Arrays类中的binarySearch方法源码解释：
            public static int binarySearch(int[] a, int key) {
                // a - [2, 64, 67, 123, 5432, 8443]
                // key - 99
                return binarySearch0(a, 0, a.length, key);
            }

                // Like public version, but without range checks.
            private static int binarySearch0(int[] a, int fromIndex, int toIndex,int key) {
                // a - [2, 64, 67, 123, 5432, 8443]
                // fromIndex - 0
                // toIndex - 6
                // key - 99

                int low = fromIndex; // 0
                int high = toIndex - 1; // 5

                while (low <= high) {
                    int mid = (low + high) >>> 1; // 2  4  3
                    int midVal = a[mid]; // 67  5432 123

                    if (midVal < key)
                        low = mid + 1; // 3
                    else if (midVal > key)
                        high = mid - 1; // 3 2
                    else
                        return mid; // key found
                }
                return -(low + 1);  // key not found. // -4
            }
 */
